package com.ssm.demo.controller;

import com.alibaba.fastjson.JSON;
import com.ssm.demo.Util.Crypt;
import com.ssm.demo.model.Result;
import org.bouncycastle.jcajce.provider.digest.MD5;
import org.bouncycastle.util.encoders.Base64;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.util.*;

@Controller
@RequestMapping("/test")
public class TestController {

    private static Map<String, String> codes = new HashMap<String, String>();
    private static final String KEY = "asdf";
    private static final String IV = "asdf";

    //生成动态码code

    @RequestMapping("/test_session")
    public @ResponseBody
    String set_sesion(HttpServletRequest request) {
        HttpSession session = request.getSession();
        String str = (String)session.getAttribute("test_session");
        if(null==str) {
            session.setAttribute("test_session","test_session");
            return "null";
        }else
            return str;
    }

    @RequestMapping(value = "/upload_file")
    public @ResponseBody
    Result upload_files(@RequestParam("file_name") MultipartFile[] files,HttpServletRequest request) throws Exception {
        HttpSession session = request.getSession();
        String str = (String)session.getAttribute("test_session");
        if(null!=str) {
            Enumeration<String> names = request.getParameterNames();
            while (names.hasMoreElements()) {
                String name = names.nextElement();
                String[] arr = request.getParameterValues(name);
                System.out.print(name + ": [");
                for (String s : arr) {
                    System.out.print(" " + s);
                }
                System.out.println(" ]");
            }

            for (MultipartFile file : files) {
                String filePath = "E:/upload/" + file.getOriginalFilename();
                System.out.println(file.getOriginalFilename());
                File f = new File(filePath);
                if (!f.exists())
                    file.transferTo(f);
            }
            return Result.ok();
        }else{
            return Result.build(406,"未登录");
        }
    }



    @RequestMapping(value = "/get_code", method = RequestMethod.POST)
    public @ResponseBody
    String post_with_files(@RequestParam("random") String random) {
        MessageDigest md5 = new MD5.Digest();
        String str = Base64.toBase64String(md5.digest(random.getBytes())).substring(0,16);
        codes.put(random, str);
        return Crypt.encode(KEY, IV, str);
    }

    @RequestMapping(value = "/post_with_files", method = RequestMethod.POST)
    public @ResponseBody
    Result post_with_files(@RequestParam("files") MultipartFile[] files, HttpServletRequest request) {
        Enumeration<String> attr_names = request.getParameterNames();
        String name, value[];
        while (attr_names.hasMoreElements()) {
            name = attr_names.nextElement();
            value = request.getParameterValues(name);
            System.out.println(name + ":");
            for (String s : value) {
                System.out.println("\t" + s);
            }
        }
        return Result.ok();
    }


    @RequestMapping(value = "/get_info", method = RequestMethod.GET)
    public @ResponseBody
    HashMap<String, Object> post_with_files(HttpServletRequest request) throws UnsupportedEncodingException {
        Enumeration<String> attr_names = request.getParameterNames();
        String name, value;
        HashMap<String, Object> res = new HashMap<String, Object>();
        while (attr_names.hasMoreElements()) {
            name = attr_names.nextElement();
            value = request.getParameterValues(name)[0];
            res.put(URLDecoder.decode(name, "utf-8"), URLDecoder.decode(value, "utf-8"));
        }
        return res;
    }

    @RequestMapping(value = "/upload_file_base64", method = RequestMethod.POST)
    public @ResponseBody
    String upload_file_base64(@RequestParam("file_name") String file_name, @RequestParam("file_content") String file_context, @RequestParam("id") String id, @RequestParam("random") String random) {
        try {
            String filePath = "E:/upload/" + file_name;
            System.out.println(filePath);
            byte[] context = Base64.decode(file_context);
            FileOutputStream os = new FileOutputStream(new File(filePath));
            os.write(context);
            os.close();
            String code = codes.remove(random);
            System.out.println("random:"+random);
            System.out.println("id:"+Crypt.decode(code,IV,id));
            return Crypt.encode(code,IV,JSON.toJSON(Result.ok()).toString());
        }catch (Exception e){
            e.printStackTrace();
        }
        return "失败";
    }


    @RequestMapping(value = "/down_load_file")
    public void down_load_file(@RequestParam("file_name") String file_name, HttpServletResponse response) throws Exception {
        String filePath = "E:/upload/" + file_name;
        File f = new File(filePath);
        if (f.exists()) {
            file_name = URLEncoder.encode(file_name, "UTF-8");
            response.reset();
            response.setHeader("Content-Disposition", "attachment; filename=\"" + file_name + "\"");
            response.addHeader("Content-Length", "" + f.length());
            response.setContentType("application/octet-stream;charset=UTF-8");
            FileInputStream fi = new FileInputStream(f);
            OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
            byte bytes[] = new byte[1024];
            int len;
            while ((len = fi.read(bytes)) > 0) {
                outputStream.write(bytes, 0, len);
            }
            outputStream.flush();
            outputStream.close();
        } else {
            response.sendError(407, "文件不存在");
        }
    }
}
